﻿using System;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;

using Teigha.DatabaseServices;
using System.Collections.Generic;
using Teigha.Runtime;
using Dwgc;
using Teigha.Geometry;
using System.IO;
using SqLiteHelper;
using Dwg_output.DCSTag;
using NPOI.DDF;

namespace Dwg_output
{
    public partial class Form1_WireDwg : Form
    {
        public Form1_WireDwg()
        {
            InitializeComponent();

        }

        static public string filePath_Excel_path;//表格所在的路径
        static public string filePath_Excel; //系统运行统一数据库路径
        static public string filePath_Db ; //系统运行统一数据库路径
        static public string filePath_Dwg; //系统运行统一数据库路径

        /// <summary>
        /// 判断文件是否存在
        /// </summary>
        /// <param name="_Path"></param>
        /// <returns></returns>
        private bool isFile(string _Path)
        {
            if (File.Exists(_Path))
                return true;
            else
                return false;

        }

        private void button1_Click(object sender, EventArgs e)
        {

             DialogResult dr = this.openFile_excel.ShowDialog();
            if (dr == DialogResult.OK)
            {
              
                filePath_Excel = this.openFile_excel.FileName;
                filePath_Excel_path = Path.GetDirectoryName(openFile_excel.FileName); // 获取文件夹路径  

                textBox1.ForeColor = Color.Red;
                textBox1.AppendText(filePath_Excel + "\r\n");
            }
            if (filePath_Excel == null) return;
           // filePath_Db = filePath_Excel_path + "\\项目.db";
            BeginWork(this,filePath_Excel, GlobalPath.WorkingDirectory);
             
        }

        private void button2_Click(object sender, EventArgs e)
        {
            filePath_Db = GlobalPath.WorkingDirectory;
            //  filePath_Db = filePath_Excel_path + "\\项目.db";
            //获取文件路径
            DialogResult dr = this.folderBrowserDialog1.ShowDialog();

            folderBrowserDialog1.Description = "Select a folder:";
            folderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer;
            //folderBrowserDialog1.SelectedPath = @"C:";

            if (dr == DialogResult.OK)//如果获取到
            {
                   
                textBox1.ForeColor = Color.Red;
                textBox1.AppendText(this.folderBrowserDialog1.SelectedPath+"\r\n");
                filePath_Dwg = folderBrowserDialog1.SelectedPath;//赋值导出目录
            }

            if (filePath_Dwg == null) return;



            //图纸导出部分
            //Task.Run(() =>
            //{
               
            List<string> jiguiID = new List<string>();
            for (int i = 0; i < 10; i++)
            {
                jiguiID.Add("1");
            }

            ////////////////////////////////////////////////////////////////////
          





            /***************************************************************************/
            /***************导出图纸部分***********************************************/
            using (Services svcs = new Services())
             {
                    using (Database sourceDb = new Database(false, true))
                    {
                        Database destDb = new Database();
                        Database sourceDb_Line = new Database(false, true);

  
                        List<string> error_list = new List<string>();
                        //if (isFile(@"../../obj/操作台模板.dwg") == true)
                        //{
                        //    sourceDb.ReadDwgFile(@"../../obj/操作台模板.dwg", FileShare.Read, true, "");
                        //}
                        //else
                        //{
                        //    MessageBox.Show("没有操作台图纸");
                        //}
                        if (isFile(@"../../Source/继电器-模拟量模板v2.7.dwg") == true)
                        {
                            sourceDb_Line.ReadDwgFile(@"../../Source/继电器-模拟量模板v2.7.dwg", FileShare.Read, true, "");
                        }
                        else
                        {
                            MessageBox.Show("没有继电器图纸");
                        }

                        //初始化字体   
                        Creat_text_Dwg textDwg = new Creat_text_Dwg(destDb); // 创建对象并初始化样式
                        Creat_text_Dwg.Init_CXC(sourceDb, destDb);
                        Wire_Dwg wire_Dwg = new Wire_Dwg();





                        int max_num = Wire_ReadSQL.Read_Max_card_id(filePath_Db, "1");
                        List<string> jiguiProject = Wire_ReadSQL.ReadJigui_Project_base(filePath_Db, 1);
                        List<string> jiguiALL = Wire_ReadSQL.ReadJiguiFromSql(filePath_Db, 1);   //判断机柜多少个

                  

                        int[] x_pos =  wire_Dwg.ALL_WriteToDwg(jiguiALL, max_num, filePath_Db, sourceDb_Line, destDb);

                        var task2 = Task.Run(() =>
                        {
                            error_list = wire_Dwg.Safe_Relay_ALL_WriteToDwg(jiguiALL, max_num, filePath_Db, sourceDb_Line, destDb);//安全栅

                        });

                        task2.Wait();

                   
                        if (error_list.Count != 0)
                        {
                            for (int i = 0; i < error_list.Count; i++)
                            {
                                textBox1.AppendText("数据库不存在：" + error_list[i] + "\r\n");
                            }

                        }

                        

                        Wire_Dwg.Tukuang_Dwg(jiguiProject, jiguiALL, x_pos, sourceDb_Line, destDb);    //加载图框

                        // 保存目标数据库为新的图纸文件
                        destDb.SaveAs(filePath_Dwg + "\\中国万岁.dwg", DwgVersion.AC1021);
                        destDb.Dispose();
                        sourceDb.Dispose();
                        sourceDb_Line.Dispose();

                        MessageBox.Show("图纸导出成功");

                        //读机柜号
                  

                        //判断机柜数量前，检查是否含有转接基座的部分

                        //如果有转接端子基座细分机柜

                        //按照机柜额外输出接线图纸








                  
                     }

                
             }
          
            // });




        }

        public void BeginWork(Form1_WireDwg formReference,string filePath_Excel,string filePath_Excel_path)
        {
            int alarm1 = 0;
            int alarm2 = 0;
            int alarm3 = 0;
            int alarm4 = 0;
            int alarm5 = 0;
            Wire_ExceltoSQL wire_ExceltoSQL = new Wire_ExceltoSQL(filePath_Excel, filePath_Excel_path);


            //创建表
            var task1 = Task.Run(() =>
            {

               alarm1 = wire_ExceltoSQL.writeExceltoSqlite();
                //if (alarm1 > 0)
                //{

                //    textBox1.AppendText("机柜数据库创建失败\r\n");

                //}
            });
          
            //读机柜号
            var task2 = task1.ContinueWith(t =>
           {

             alarm2 = wire_ExceltoSQL.read_Jigui(filePath_Excel, filePath_Excel_path );

           });
            var task5 = task1.ContinueWith(t =>
            {

              alarm5 = wire_ExceltoSQL.read_sys_Jigui(filePath_Excel, filePath_Excel_path );

            });
    
            //读取项目信息
            var task3 = task1.ContinueWith(t =>
            {
           //  alarm3 = wire_ExceltoSQL.read_Project(filePath_Excel, filePath_Excel_path );

            });
            //读取位号信息
            var task4 = Task.WhenAll(task2, task5).ContinueWith(t =>
            {
              alarm4 = wire_ExceltoSQL.read_Tag(formReference,filePath_Excel, filePath_Excel_path);

            });




            // 当task1任务完成后，将消息添加到textBox  
            task1.ContinueWith(t =>
            {
                this.Invoke(new Action(() =>
                {

                    textBox1.AppendText("数据库创建成功\r\n");


                }));
            });
            task2.ContinueWith(t =>
            {
                this.Invoke(new Action(() =>
                {
                    if (alarm2 > 0)
                    {
                        textBox1.AppendText("机柜信息已经读取成功\r\n");
                    }

                }));
            });
            task3.ContinueWith(t =>
            {
                this.Invoke(new Action(() =>
                {
                    if (alarm3 > 0)
                    {
                        
                        textBox1.AppendText("项目与信息读取成功\r\n");
                    }

                }));
            });
            task5.ContinueWith(t =>
            {
                this.Invoke(new Action(() =>
                {
                    if (alarm5 > 0)
                    {

                        textBox1.AppendText("系统机柜读取成功\r\n");
                    }

                }));
            });



            //所有任务完成后。
            Task.WhenAll(task1, task2, task3, task4).ContinueWith(t =>
              {
                  this.Invoke(new Action(() =>
                  {
                     
                     
                      if (alarm4 > 0)
                      {
                          textBox1.ForeColor = Color.Blue;
                          textBox1.AppendText("位号信息已经读取成功\r\n");
                      }




                      textBox1.ForeColor = Color.Blue;
                      textBox1.AppendText("所有任务已完成\r\n");
                  }));
              });

        }

        public void BeginWork2(Form1_WireDwg formReference, string filePath_Excel, string filePath_Excel_path)
        {
            int alarm1 = 0;
            int alarm2 = 0;
            int alarm3 = 0;
            int alarm4 = 0;
            int alarm5 = 0;
            Wire_DcsTagToExcel wire_ExceltoSQL = new Wire_DcsTagToExcel(filePath_Excel, filePath_Excel_path);


            //创建表
            var task1 = Task.Run(() =>
            {

                alarm1 = wire_ExceltoSQL.writeExceltoSqlite();
              
            });

            //读机柜号
            var task2 = task1.ContinueWith(t =>
            {

                alarm2 = wire_ExceltoSQL.Read_DCStag_device( (filePath_Excel_path + "\\项目.db"));


            });
          

      



            // 当task1任务完成后，将消息添加到textBox  
            task1.ContinueWith(t =>
            {
                this.Invoke(new Action(() =>
                {

                    textBox1.AppendText("数据库创建成功\r\n");


                }));
            });
            task2.ContinueWith(t =>
            {
                this.Invoke(new Action(() =>
                {
                    if (alarm2 > 0)
                    {
                        textBox1.AppendText("机柜信息已经读取成功\r\n");
                    }

                }));
            });
         



            //所有任务完成后。
            Task.WhenAll(task1, task2).ContinueWith(t =>
            {
                this.Invoke(new Action(() =>
                {


                    if (alarm4 > 0)
                    {
                        textBox1.ForeColor = Color.Blue;
                        textBox1.AppendText("卡件已经读取成功\r\n");
                    }




                    textBox1.ForeColor = Color.Blue;
                    textBox1.AppendText("所有任务已完成\r\n");
                }));
            });

        }
        private void button3_Click(object sender, EventArgs e)
        {

            //using (Services svcs = new Services())
            //{
            //    using (Database sourceDb = new Database(false, true))
            //    {
            //        Database destDb = new Database();
            //        Database sourceDb_sysDCS = new Database(false, true);


            //        if (isFile(@"../../obj/操作台模板.dwg") == true)
            //        {
            //            sourceDb.ReadDwgFile(@"../../obj/操作台模板.dwg", FileShare.Read, true, "");
            //        }
            //        if (isFile(@"../../obj/DCS块.dwg") == true)
            //        {
            //            sourceDb_sysDCS.ReadDwgFile(@"../../obj/DCS块.dwg", FileShare.Read, true, "");
            //        }



            //        //初始化字体   
            //        Creat_text_Dwg textDwg = new Creat_text_Dwg(destDb); // 创建对象并初始化样式
            //        //加载图框
            //        Creat_text_Dwg.ctrateText("晨444444444星吃", destDb, new Point3d(100, 0, 0), 50, 0, 2);

            //        Creat_text_Dwg.ctrateText("aaaaaaaaaaaaaaaaaaa", destDb, new Point3d(100, 200, 0), 50, 0, 2);






            //        // 保存目标数据库为新的图纸文件
            //        destDb.SaveAs("C:\\Users\\Cxc\\Desktop" + "\\中国万岁.dwg", DwgVersion.AC1021);
            //        destDb.Dispose();
            //        sourceDb.Dispose();
            //        sourceDb_sysDCS.Dispose();


            //        MessageBox.Show("图纸导出成功");




            //    }


            //}

          


         
        }

        private void Form1_WireDwg_Load(object sender, EventArgs e)
        {
            textBox1.AppendText(GlobalPath.WorkingDirectory??"kong");

        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (filePath_Excel_path==null)
            {
                MessageBox.Show("请导入表格文件，或者打开数据库");
                return;
            }
            else
            {
                return;
            } 
            textBox1.AppendText("统计BOM如下;\r\n" );
            Output_Bom output_Bom = new Output_Bom(filePath_Excel_path + "\\项目.db");
            Dictionary<int,string > Dict_jigui  = output_Bom.readjigui_Dictionary();
            List<Dictionary<string,int>> bom_ter_bord = output_Bom.read1();




            for (int i = 0; i < bom_ter_bord.Count; i++)
            {
                string value;
                if (Dict_jigui.TryGetValue(i + 1, out value))
                {
                    // 如果键存在于字典中，输出键和值  
                    Console.WriteLine($"The key {i + 1} has the value {value}.");
                    textBox1.AppendText(value + "\r\n");

                }
                foreach (var item in bom_ter_bord[i])
                {
                    textBox1.AppendText(item.Key +"    "+ item.Value.ToString()+"个"+"\r\n");
                }

            } 
            

        }

        private void toolStripTextBox1_Click(object sender, EventArgs e)
        {

        }
        public ProgressBar ProgressBar1
        {
            get { return progressBar1; }
            set { progressBar1 = value; }

        }
        public Label label
        {
            get { return label1; }
            set { label1 = value; }

        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void dCS卡件导入ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 导入ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void dCS卡件导出ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }
    }
}
